package com.sanpu.kxe.business.card.presenter;

import com.sanpu.kxe.business.card.bean.BankInfoOutput;
import com.sanpu.kxe.business.card.contract.BankListContract;
import com.sanpu.kxe.business.card.model.CardModel;
import com.sanpu.kxe.rxservice.RxError;
import com.sanpu.kxe.utils.ToastUtil;

import java.net.SocketTimeoutException;
import java.util.List;

import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Description：银行卡列表
 * Created by 薛勇军 on 2019/4/12.
 */

public class BankListPresenter implements BankListContract.Presenter {

    private BankListContract.View mView;

    private CompositeSubscription mSubscription;

    private String cardType;

    public BankListPresenter(BankListContract.View mView, String cardType) {
        this.mView = mView;
        this.cardType = cardType;
        mSubscription = new CompositeSubscription();
    }

    @Override
    public void selectUrmBankPage() {
        Subscription subscription = CardModel.getInstance().selectUrmBankPage(cardType)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<BankInfoOutput>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        if (e instanceof RxError) {
                            RxError error = (RxError) e;
                            ToastUtil.showTextViewPrompt(error.getMessage());
                        } else if (e instanceof SocketTimeoutException) {
                            ToastUtil.showTextViewPrompt("网络连接超时!");
                        } else {
                            ToastUtil.showTextViewPrompt("网络连接异常!");
                        }
                        mView.showViewData(null);
                    }

                    @Override
                    public void onNext(List<BankInfoOutput> bankInfoOutputs) {
                        mView.showViewData(bankInfoOutputs);
                    }
                });
        mSubscription.add(subscription);
    }

    @Override
    public void onDestroyPresenter() {
        if (mSubscription != null && !mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
            mSubscription = null;
        }
        if (mView != null) {
            mView = null;
        }
    }
}
